package com.personalblog.realm;

import com.personalblog.handler.ApiNotFindUserException;
import com.personalblog.po.User;
import com.personalblog.service.UserService;
import com.personalblog.service.serviceImpl.UserServiceImpl;
import com.personalblog.vo.UserPermissionVo;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import javax.sound.sampled.Line;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 自定义Realm
 * @author jxau_scf
 * @date 2021/4/20 - 11:04
 */
public class UserShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    public void setUserService(UserService userService){
        this.userService = userService;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String userName = (String)principalCollection.getPrimaryPrincipal();
        if (userName == null){
            throw new ApiNotFindUserException("未登录");
        }
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        Set<String> roles = new HashSet<>();
        Set<String> stringPermissions = new HashSet<>();
        List<UserPermissionVo> list = userService.queryUserPermission(userName);
        for (UserPermissionVo userPermissionVo : list){
            roles.add(userPermissionVo.getRoleCode());
            stringPermissions.add(userPermissionVo.getPermCode());
        }
//        roles.add("USER");
//        stringPermissions.add("USER:DELETE");//角色:权限

        simpleAuthorizationInfo.setRoles(roles);//角色可以通过数据库查询得到
        simpleAuthorizationInfo.setStringPermissions(stringPermissions);//权限可以通过数据库查询得到
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String username = usernamePasswordToken.getUsername();
        User user = userService.findUserByUserName(username);
        if (null == user){
            throw new ApiNotFindUserException("未知账号");
        }
        //封装数据库中查询出的用户信息，用于接下来的密码验证
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUserName(), user.getPassword().toCharArray(), getName());
        return authenticationInfo;
    }

}
